﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Records;
using Orchard.Core.Settings.Metadata.Records;
using SchoolPointe.RelatedContent.Enums;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using System;

namespace SchoolPointe.RelatedContent.Models
{
    [DataContract]
    public class RelatedContentRelationship
    {
        public RelatedContentRelationship() { }
        public RelatedContentRelationship(string json)
        {            
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) {
                var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType());
                var temp = serializer.ReadObject(ms) as RelatedContentRelationship;
                this.Name = temp.Name;
                this.Identifier = temp.Identifier;
                this.RelationType = temp.RelationType;
                this.IsRequired = temp.IsRequired;
                this.ContentTypeLimitations = temp.ContentTypeLimitations;
                this.EditorView = temp.EditorView;
                this.InverseOf = temp.InverseOf;
            }
        }

        [DataMember]
        [Required]
        public string Name { get; set; }

        [DataMember]
        public string Identifier { get; set; }
        
        public RelationType RelationType { get; set; }

        [DataMember(Name = "RelationType")]
        private string _relationTypeToSerialize
        {
            get
            {
                return Enum.GetName(this.RelationType.GetType(), this.RelationType);
            }
            set
            {
                this.RelationType = (RelationType)Enum.Parse(typeof(RelationType), value);
            }
        }

        [DataMember]
        public bool IsRequired { get; set; }

        [DataMember]
        [Required]
        [DisplayName("Content Types")]
        public string ContentTypeLimitations { get; set; }

        [DataMember]
        [DisplayName("Editor View")]
        public string EditorView { get; set; }

        [DataMember]
        [DisplayName("Inverse Of")]
        public string InverseOf { get; set; }

        public string ToJson()
        {
            string json;

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType());
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, this);
                json = Encoding.Default.GetString(ms.ToArray());
            }

            return json;
        }
    }
}